using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.Reflection;

namespace zeroflag.Parserz.IDE
{
	public partial class TokenEditor : TokenBase, ISelectedItems<TokenNode>
	{
		List<Type> m_AdditionalTypes = new List<Type>();

		XmlSerializer m_Serializer;
		public TokenEditor()
		{
			InitializeComponent();
		}

		[System.ComponentModel.Category("Parser")]
		public zeroflag.Parserz.Token Root
		{
			get { return this.Controller.Root; }
			set
			{
				this.Controller.Root = value;
				this.Invalidate();
			}
		}

		protected XmlSerializer Serializer
		{
			get { return m_Serializer; }
			set { m_Serializer = value; }
		}

		protected virtual string SettingsPath
		{
			get { return System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TokenView.TokenBox.settings"); }
		}

		public List<Type> AdditionalTypes
		{
			get { return m_AdditionalTypes; }
		}

		protected List<Type> GetDerivedTypes<T>()
		{
			List<Type> derived = new List<Type>();
			foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
			{
				Type[] types;
				try
				{
					types = assembly.GetTypes();
				}
				catch (System.Reflection.ReflectionTypeLoadException exc)
				{
					types = exc.Types;
				}
				foreach (Type type in types)
				{
					if (type != null && type.IsSubclassOf(typeof(T)))
					{
						derived.Add(type);
					}
				}
			}
			return derived;
		}

		protected List<Type> GetSerializeTypes<T>()
		{
			if (this.AdditionalTypes.Count <= 0)
				return this.GetDerivedTypes<T>();
			else
			{
				List<Type> types = this.GetDerivedTypes<T>();
				types.AddRange(this.AdditionalTypes);
				return types;
			}
		}

		public virtual void SettingsStore()
		{
			try
			{
				if (this.Serializer == null)
					this.Serializer = new XmlSerializer(this.GetType(), this.GetSerializeTypes<Token>().ToArray());

			}
			catch (Exception exc)
			{
				Console.WriteLine(exc);
			}
		}

		public virtual void SettingsRestore()
		{
			try
			{
				if (this.Serializer == null)
				{
					List<Type> types = this.GetSerializeTypes<TokenNode>();
					this.Serializer = new XmlSerializer(typeof(TokenNode), types.ToArray());
				}

			}
			catch (Exception exc)
			{
				Console.WriteLine(exc);
			}
		}

		#region ISelectedItems<object> Members


		#endregion

		#region ISelectedItems<TokenNode> Members

		public List<TokenNode> SelectedItems
		{
			get
			{
				return MainForm.FindParent<ISelectedItems<TokenNode>>(this.Parent).SelectedItems;
			}
			set
			{
			}
		}

		#endregion
	}
}
